package com.example.demo.service;

import com.example.demo.model.AIMessage;
import com.example.demo.model.ProductInfo;
import io.github.briqt.spark4j.*;
import io.github.briqt.spark4j.constant.SparkApiVersion;
import io.github.briqt.spark4j.model.SparkMessage;
import io.github.briqt.spark4j.model.SparkSyncChatResponse;
import io.github.briqt.spark4j.model.request.SparkRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Service
public class SparkAIService {
    private final SparkClient sparkClient;
    private final AIChatSessionService sessionService;
    private final ProductService productService;

    public SparkAIService(SparkClient sparkClient, AIChatSessionService sessionService, ProductService productService) {
        this.sparkClient = sparkClient;
        this.sessionService = sessionService;
        this.productService = productService;
    }

    public CompletableFuture<String> chat(String sessionId, String content) {
        List<SparkMessage> messages = new ArrayList<>();
        
        // 获取历史消息
        List<AIMessage> history = sessionService.getHistory(sessionId);
        for (AIMessage msg : history) {
            messages.add(SparkMessage.userContent(msg.getContent()));
        }
        
        // 获取商品数据
        List<ProductInfo> products = productService.getAllProducts();
        StringBuilder productInfo = new StringBuilder();
        productInfo.append("商品列表：\n");
        
        for (ProductInfo product : products) {
            String productDetail = String.format(
                "[商品%d]\n" +
                "名称：%s\n" +
                "当前价格：%s元\n" +
                "原价：%s元\n" +
                "品牌：%s\n" +
                "描述：%s\n" +
                "商品状况：%s\n" +
                "发货地：%s\n" +
                "运费：%s元\n" +
                "商品分类ID：%d\n" +
                "人气指数：%d次浏览，%d次收藏\n" +
                "上架时间：%s\n\n",
                product.getId(), product.getName(), 
                String.valueOf(product.getPrice()),
                String.valueOf(product.getOriginalPrice()),
                product.getBrand(), product.getDescription(),
                product.getConditionLevel(), product.getLocation(),
                String.valueOf(product.getShippingFee()),
                product.getCategoryId(),
                product.getViewCount(), product.getFavoriteCount(),
                product.getCreateTime()
            );
            productInfo.append(productDetail);
        }
        
        // 构建系统提示
        String systemPrompt = "你是一个专业的购物推荐助手，擅长基于用户需求和历史对话推荐最合适的商品。\n\n" +
                             "商品信息字段说明：\n" +
                             "- ID：商品的唯一标识符\n" +
                             "- 名称：商品的官方名称\n" +
                             "- 当前价格：商品的实际销售价格（单位：元）\n" +
                             "- 原价：商品的原始标价（单位：元）\n" +
                             "- 品牌：商品的品牌名称\n" +
                             "- 描述：商品的详细特点和功能说明\n" +
                             "- 商品状况：商品的新旧程度\n" +
                             "- 发货地：商品的发货地点\n" +
                             "- 运费：商品的配送费用\n" +
                             "- 商品分类：商品所属的类别\n" +
                             "- 人气指数：包含浏览次数和收藏次数，反映商品受欢迎程度\n" +
                             "- 上架时间：商品开始销售的时间\n\n" +
                             "回复要求：\n" +
                             "1. 仔细分析用户的当前需求和历史对��内容\n" +
                             "2. 优先推荐最符合用户需求的商品\n" +
                             "3. 如果用户提到价格区间，严格遵守价格限制\n" +
                             "4. 如果找不到完全匹配的商品，说明原因并推荐最接近的选项\n" +
                             "5. 使用礼貌友好的语气，给出专业的推荐理由\n\n" +
                             "回复格式：\n" +
                             "推荐商品ID：[商品ID]\n" +
                             "推荐理由：[基于用户需求的具体推荐理由]\n\n" +
                             "可选商品列表：\n" +
                             productInfo.toString();

        // 打印完整的发送消息
        log.info("发送给讯飞星火的系统提示：\n{}", systemPrompt);
        log.info("发送给讯飞星火的用户输入：{}", content);
        
        messages.add(SparkMessage.systemContent(systemPrompt));
        messages.add(SparkMessage.userContent(content));
        
        SparkRequest sparkRequest = SparkRequest.builder()
                .messages(messages)
                .maxTokens(2048)
                .temperature(0.3)
                .apiVersion(SparkApiVersion.V4_0)
                .build();

        return CompletableFuture.supplyAsync(() -> {
            try {
                SparkSyncChatResponse response = sparkClient.chatSync(sparkRequest);
                String reply = response.getContent();
                log.info("讯飞星火的回复：{}", reply);
                
                // 保存对话历史
                sessionService.addMessage(sessionId, new AIMessage("user", content));
                sessionService.addMessage(sessionId, new AIMessage("assistant", reply));
                
                return reply;
            } catch (Exception e) {
                log.error("AI对话发生错误: {}", e.getMessage());
                throw e;
            }
        });
    }
} 